package Demo3;

import com.sun.source.tree.Tree;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-07-27
 * Time: 19:48
 */
public class BinarySearchTree {

    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public TreeNode root;

    //添加
    public void addNode(int val){
        TreeNode node = new TreeNode(val);
        if(root == null){
            root = node;
            return;
        }
        TreeNode cur = root;
        TreeNode prev = null;
        while(cur != null){
            if(cur.val == val){
                return;
            }else if(cur.val > val){
                prev = cur;
                cur = cur.left;
            }else{
                prev = cur;
                cur = cur.right;
            }
        }
        if(prev.val > val){
            prev.left = node;
        }else{
            prev.right = node;
        }
    }

    //查找
    public TreeNode searchNode(int val){
        TreeNode cur = root;
        while(cur != null){
            if(cur.val == val){
                return cur;
            }else if(cur.val > val){
                cur = cur.left;
            }else{
                cur = cur.right;
            }
        }
        return null;
    }


    private void remove(TreeNode cur,TreeNode prev){
        if(cur.left == null && cur.left != null){
            if(cur == root){
                root = cur.right;
            }else if(prev.left == cur){
                prev.left = cur.right;
            }else{
                prev.right = cur.left;
            }
            return;
        }
        if(cur.left != null && cur.left == null){
            if(cur == root){
                root = cur.left;
            }else if(prev.left == cur){
                prev.left = cur.left;
            }else{
                prev.right = cur.left;
            }
            return;
        }
        if(cur.left != null && cur.left != null){
            TreeNode target = cur.right;
            TreeNode targetPater = cur;
            while(target.left != null){
                targetPater = target;
                target = target.left;
            }
            cur.val = target.val;
            if(cur == targetPater){
                targetPater.right = target.right;
            }else{
                targetPater.left = null;
            }
        }
    }
    //删除
    public void removeNode(int val){
        //找到该节点
        TreeNode cur = root;
        TreeNode prev = null;
        while(cur != null){
            if(cur.val == val){
                remove(cur,prev);
                return;
            }else if(cur.val > val){
                prev = cur;
                cur = cur.left;
            }else{
                prev = cur;
                cur = cur.right;
            }
        }

    }
}